/**
 * Author：LSP
 * Date：2020-11-30
 */

//================================================
// 登录ins获取对应的sessionid填入
const sessionid = ""
// 自行按照下面格式修改添加
const user_name_arr = [
    'lalalalisa_m',
    'jaychou'
]
// 是否显示用户名
const show_user_name = true
//------------------------------------------------
// 脚本名字
const name = Script.name()
// 文件
const fm = FileManager.local()
//================================================

if (!config.runsInWidget) {
    // 运行弹窗检查
    let message = '检查弹窗'
    let options = ['预览脚本', "同步脚本"]
    const synchronousIndex = 1
    let cancelText = '取消'
    let response = await generateListAlert(message, options, cancelText)
    let selectIndex = response.selectIndex
    if (selectIndex == synchronousIndex) {
        await updateScriptableAlert()
    } else {
        await runWidget()
    }
} else {
    // 直接运行脚本
    await runWidget()
}


/**
 * 更新脚本弹窗
 */
async function updateScriptableAlert() {
    // 脚本更新替换
    const js_url = 'https://gitee.com/enjoyee/scriptable/raw/master/ins.js'
    const req = new Request(js_url)
    const codeString = await req.loadString()
    fm.writeString(module.filename, codeString)

    // 通知
    message = '提示'
    options = ['重新进入替换session运行']
    cancelText = '确定'
    response = await generateListAlert(message, options, cancelText)

    // 完成
    Script.complete()
}

/**
 * 运行脚本
 */
async function runWidget() {
    // 用户名索引值
    const user_index_last = 'user_index_last'
    // 随机用户索引
    const user_size = user_name_arr.length
    let user_index = 0
    if (Keychain.contains(user_index_last)) {
        const last = Keychain.get(user_index_last)
        user_index = parseInt(last) + 1
    }
    if (user_index >= user_size) {
        user_index = 0
    }

    // 用户名
    let user_name = user_name_arr[user_index]

    // 图片缓存目录
    let pic_cache_path = fm.joinPath(fm.documentsDirectory(), `lsp-ins-cache-${name}`)
    // 图片
    let image = undefined
    // 链接
    const url = `https://www.instagram.com/${user_name}/`
    try {
        const json = await loadInsJsonData(url)
        const profile_page = json.entry_data.ProfilePage
        if (profile_page.length == 0) {
            log(`获取数据失败...`)
            return
        }
        const edges = profile_page[0].graphql.user.edge_owner_to_timeline_media.edges

        // 图片索引值
        const pic_index_last = `pic_index_last_${user_name}`
        // 随机图片索引
        const pic_size = edges.length
        let pic_index = 0
        if (Keychain.contains(pic_index_last)) {
            const last = Keychain.get(pic_index_last)
            pic_index = parseInt(last) + 1
        }
        if (pic_index >= pic_size) {
            pic_index = 0
        }

        // item
        const element = edges[pic_index].node;
        // 图片链接
        const img_url = element.display_url
        // like数量
        const like_count = element.edge_liked_by.count
        // comment数量
        const comment_count = element.edge_media_to_comment.count

        // 加载图片
        const req = new Request(img_url)
        image = await req.loadImage()
        // 图片写入缓存
        fm.writeImage(pic_cache_path, image)
        // 保存当前用户索引
        Keychain.set(user_index_last, `${user_index}`)
        // 保存当前图片索引
        Keychain.set(pic_index_last, `${pic_index}`)
    } catch (e) {
        log(`加载出错：${e}`)
        // 读取上次图片的缓存
        image = fm.readImage(pic_cache_path)
        // 用户名置空
        user_name = ""
    }


    ////////////////////////////////////////
    // 创建组件
    const widget = new ListWidget()
    widget.url = url
    // 作者名字显示控制
    if (show_user_name && user_name.length > 0) {
        widget.setPadding(0, 0, 0, 0)
        const info_stack = widget.addStack()
        info_stack.layoutVertically()
        // 下对齐
        info_stack.addSpacer()
        const name_stack = info_stack.addStack()
        // 添加显示用户名
        const text_span = name_stack.addText(`@${user_name}`)
        // padding
        info_stack.setPadding(10, 10, 5, 10)
        text_span.lineLimit = 1
        text_span.font = Font.systemFont(12)
        text_span.textColor = new Color('ffffff')
        // 透明度
        text_span.textOpacity = 0.8
        // 左对齐
        name_stack.addSpacer()
    }

    // 图片
    widget.backgroundImage = image
    widget.presentSmall()
    Script.setWidget(widget)
    Script.complete()
    ////////////////////////////////////////
}


//================================================

/**
 * 弹窗
 * @param {信息} message 
 * @param {选项} options 
 * @param {输入框} textInput 
 * @param {输入框提示} textInputHint 
 */
async function generateAlert(message, options, textInput = false, textInputHint) {
    const alert = new Alert()
    alert.message = message

    if (textInput) {
        alert.addTextField(`${textInputHint}`, '')
    }

    for (const option of options) {
        alert.addAction(option)
    }

    let select_index = await alert.presentAlert()
    let text_input = alert.textFieldValue()

    return {
        selectIndex: select_index,
        textFieldValue: text_input
    }
}


/**
 * 列表形弹窗
 * @param {信息} message 
 * @param {选项} options 
 * @param {取消文字} cancelText 
 */
async function generateListAlert(message, options, cancelText) {
    const alert = new Alert()
    alert.message = message

    for (const option of options) {
        alert.addAction(option)
    }

    alert.addCancelAction(cancelText)

    let select_index = await alert.present()

    return {
        selectIndex: select_index
    }
}


/**
 * 获取json
 * @param {*} user_name 用户名
 */
async function loadInsJsonData(url) {
    const request = new Request(url)
    const defaultHeaders = {
        "cookie": `sessionid=${sessionid};`
    }
    request.method = 'GET'
    request.headers = defaultHeaders

    const data = await request.loadString()
    const json = data.match(/(window._sharedData\s?)(=\s?)(.*?);<\/script>/)[3]

    return JSON.parse(json)
}
//==================================================================//


